package com.avecsys.quotemanager.mbeans.buyer;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.faces.model.SelectItem;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.avecsys.quotemanager.constants.ApplicationConstants;
import com.avecsys.quotemanager.dao.common.EnumActor;
import com.avecsys.quotemanager.dao.common.EnumTransactionStatus;
import com.avecsys.quotemanager.exception.BaseException;
import com.avecsys.quotemanager.exception.BusinessException;
import com.avecsys.quotemanager.exception.UserSessionNotFoundException;
import com.avecsys.quotemanager.mbeans.core.BaseMBean;

import com.avecsys.quotemanager.pojos.BuyerMasterPojo;
import com.avecsys.quotemanager.pojos.BuyerUsersPojo;
import com.avecsys.quotemanager.pojos.CountryMasterPojo;
import com.avecsys.quotemanager.pojos.SupplierUsersPojo;
import com.avecsys.quotemanager.pojos.UserMasterPojo;

import com.avecsys.quotemanager.service.buyer.BuyerMasterService;
import com.avecsys.quotemanager.service.common.CommonService;

import com.avecsys.quotemanager.utils.MessageBoardUtil;
import com.avecsys.quotemanager.utils.SelectItemUtils;
import com.avecsys.quotemanager.utils.SystemConfig;
import com.avecsys.quotemanager.utils.TransactionStatus;
import com.avecsys.quotemanager.vo.BuyerVO;


public class BuyerMasterMBean extends BaseMBean implements Serializable{

	private final Log log = LogFactory.getLog(BuyerMasterMBean.class);

	private BuyerMasterService buyerMasterService;

	private CommonService commonService;

	private BuyerMasterPojo buyerMasterPojo = new BuyerMasterPojo();

	private List<SelectItem> countrySelectItemList = new ArrayList<SelectItem>();

	private String defaultAdminUserEmail;

	public String getDefaultAdminUserEmail() {
		return defaultAdminUserEmail;
	}

	public void setDefaultAdminUserEmail(String defaultAdminUserEmail) {
		this.defaultAdminUserEmail = defaultAdminUserEmail;
	}

	public String actionCancel() {
		return "cancel";
	}

	public String actionSaveBuyerMaster() {
		try {
			log.info("Started Saving Buyer Information into database");
			// Step1: Update user modification information
			updateUserInformation(buyerMasterPojo);
			
			// Step2: Update Logged in user Supplier to Buyer
			UserMasterPojo userMasterPojo = getSignedInUser();
			for (SupplierUsersPojo supplierUsersPojo : userMasterPojo
					.getSupplierUsersPojo()) {
				buyerMasterPojo.setSupplierMasterPojo(supplierUsersPojo
						.getSupplierMasterPojo());
			}
			// Step3: Save Buyer Master Information
			// Prepare Value Object to carry supplier information and default
			// user email address
			BuyerVO buyerVO = new BuyerVO();
			buyerVO.setBuyerMasterPojo(buyerMasterPojo);
			buyerVO.setDefaultAdminUserEmail(defaultAdminUserEmail);

			TransactionStatus transactionStatus = buyerMasterService
					.saveBuyerMaster(buyerVO);
			MessageBoardUtil.publishTransactionStatusMessage(transactionStatus,
					EnumActor.BUYER, "messageBoardId", "",
					new Object[] { buyerMasterPojo.getCompanyMasterPojo()
							.getCompanyName() });
			// Send Verification Email
			if (transactionStatus.getStatus().intValue() == EnumTransactionStatus.SAVE_SUCESS
					.ordinal()) {
				log.info("Sending Activate Email Notification to Supplier Admin User");
				for (BuyerUsersPojo BuyerUsersPojo : buyerMasterPojo.getBuyerUsers()) {
					if (Boolean.FALSE.toString().equals(
							BuyerUsersPojo.getUserMasterPojo()
									.getEmailVerfied())) {
						//commonService.sendEmail(BuyerUsersPojo);
					}
				}
			}
			log.info("Completed saving buyer information into database sucessfully");
		} catch (BaseException e) {
			log.error(e);
			MessageBoardUtil.publishException(e);
		} catch (Exception e) {
			log.error(e);
			MessageBoardUtil.publishException(e);
		}
		return "openBuyerListScreen";
	}

	/**
	 * @return the commonService
	 */
	public CommonService getCommonService() {
		return commonService;
	}

	/**
	 * @return the countrySelectItemList
	 */
	public List<SelectItem> getCountrySelectItemList() {
		return countrySelectItemList;
	}




	public BuyerMasterService getBuyerMasterService() {
		return buyerMasterService;
	}

	public void setBuyerMasterService(BuyerMasterService buyerMasterService) {
		this.buyerMasterService = buyerMasterService;
	}

	public BuyerMasterPojo getBuyerMasterPojo() {
		return buyerMasterPojo;
	}

	public void setBuyerMasterPojo(BuyerMasterPojo buyerMasterPojo) {
		this.buyerMasterPojo = buyerMasterPojo;
	}

	/**
	 * Method to load all the countries and default to system default country in
	 * new supplier case
	 */
	public void loadAllCountries() {
		try {
			List<CountryMasterPojo> countryMasterPojoList = commonService
					.getAllCountries(new CountryMasterPojo());
			// Set Default Country
			String defaultCountryCode = SystemConfig
					.getProperty(ApplicationConstants.SUPPLIER_DEFAULT_COUNTRY);
			if (!buyerMasterPojo.isPersisted()) {
				buyerMasterPojo.getCompanyMasterPojo()
						.getCountryMasterPojo().setCode(defaultCountryCode);
			}
			List<SelectItem> countrySelectItemList = SelectItemUtils
					.convertCountryToSelectItems(countryMasterPojoList);
			setCountrySelectItemList(countrySelectItemList);
		} catch (BusinessException e) {
			log.error(e);
		}

	}

	/**
	 * @param commonService
	 *            the commonService to set
	 */
	public void setCommonService(CommonService commonService) {
		this.commonService = commonService;
	}

	/**
	 * @param countrySelectItemList
	 *            the countrySelectItemList to set
	 */
	public void setCountrySelectItemList(List<SelectItem> countrySelectItemList) {
		this.countrySelectItemList = countrySelectItemList;
	}


	/**
	 * Method to update the user information
	 * 
	 * @param buyerMasterPojo
	 * @throws UserSessionNotFoundException
	 */
	public void updateUserInformation(BuyerMasterPojo buyerMasterPojo)
			throws UserSessionNotFoundException {
		// Update User Information to Buyer
		super.updateUserInformation(buyerMasterPojo, null);
		// Update User Information to Company
		super.updateUserInformation(buyerMasterPojo.getCompanyMasterPojo(),
				buyerMasterPojo.getModifiedDttm());
	
	}
}
